import datetime

from django.shortcuts import render

# Create your views here.
from rest_framework import viewsets, authentication
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from rest_framework.schemas import AutoSchema
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import filters
from rest_framework.permissions import IsAuthenticated

from competition.models import CompetitionSeason
from school.models import School
from student.filter import StudentFilter
from student.models import Student
from student.serializers import StudentCreateSerializer, StudentListSerializer, StudentGroupingSerializer
from rest_framework.decorators import action
from dateutil.relativedelta import relativedelta

from utils.commonFunctions import average, calculate_age
from xlrd import xldate_as_tuple


class StudentPagination(PageNumberPagination):
    page_size = 10
    page_size_query_param = 'page_size'
    page_query_param = "page"


class StudentViewSet(viewsets.ModelViewSet):
    """
        学员信息
        list:
          获取学员信息
        grouping:
            按需分组
        create:
          添加学员信息
        retrieve:
            获取单独学员信息
        update:
          全部更新学员信息
        partial_update:
           部分更新学员信息
        delete:
          删除学员信息
    """
    authentication_classes = (JSONWebTokenAuthentication, authentication.SessionAuthentication)  # jwt和session认证
    pagination_class = StudentPagination  # 分页
    filter_backends = (DjangoFilterBackend, filters.SearchFilter,
                       filters.OrderingFilter
                       )  # 过滤，一般为choice和外键
    filter_class = StudentFilter
    search_fields = ('student_name','contact_name',
                     'contact_phone',
                     'ID_number', 'birth_date',
                     'registration_date')  # 搜索，文字字段，
    ordering_fields = ('gender', 'payment_status', 'birth_date')  # 排序

    def get_serializer_class(self):
        if self.action in ["create", "partial_update"]:
            return StudentCreateSerializer
        return StudentListSerializer

    def get_permissions(self):  # 动态获取权限
        if self.action in ["list", "retrieve",'create']:  # 用户注册时，不需要权限认证
            return []
        return [IsAuthenticated()]

    def get_queryset(self):
        if self.request.user.is_superuser:  # 管理员
            return Student.objects.all()
        elif self.request.user.id == None:
            return None
        else:
            return Student.objects.filter(school=self.request.user.school.id)


    @action(methods=['get'], detail=False, permission_classes=[IsAuthenticated], url_path='grouping')
    def grouping(self, request, *args, **kwargs):
        match_date = request.query_params.get('match_date')
        try:
            group_num = int(request.query_params.get('group_num'), 10)
            age = int(request.query_params.get('age', 1))
        except Exception as e:
            data = {'detail': e}
            return Response(data=data, status=400)
        student_list = Student.objects.filter(payment_status=1).order_by('birth_date')
        if self.request.user.is_superuser:  # 管理员
            student_list = student_list
        elif self.request.user.id == None:
            student_list = None
        else:
            student_list = Student.objects.filter(school=self.request.user.school.id)
        if student_list and match_date:
            try:
                now_data = datetime.date(*map(int, match_date.split('-'))) - relativedelta(years=age - 1)
                entry_data = datetime.date(*map(int, match_date.split('-'))) - relativedelta(years=age)
            except Exception as e:
                data = {'detail': e}
                return Response(data=data, status=400)
            student_gender_list = student_list.filter(birth_date__lt=now_data, birth_date__gte=entry_data)
            queryset = self.filter_queryset(student_gender_list)

            # page = self.paginate_queryset(queryset)  # 分页，这里不需要
            # if page is not None:
            #     serializer = self.get_serializer(page, many=True)
            #     return self.get_paginated_response(serializer.data)
            serializer = self.get_serializer(queryset, many=True)
            men_list = []
            women_list = []
            for i in serializer.data:
                birth = datetime.date(*map(int, i['birth_date'].split('-')))
                match = datetime.date(*map(int, match_date.split('-')))
                i['age'] = calculate_age(birth, match)
                if int(i['gender']['key']) == 0:  # 男子
                    men_list.append(i)
                else:
                    women_list.append(i)
            # serializer = StudentGroupingSerializer(queryset, many=True)
            average_men = average(men_list, group_num)  # 男子平均分组
            average_women = average(women_list, group_num)  # 女子平均分组
            results = [
                {0: average_men},
                {1: average_women}
            ]
            data = {
                "count": queryset.count(),
                'age': age,
                "results": results
            }

        else:
            data = {
                "count": 0,
                'age': age,
                "results": []
            }
        return Response(data=data, status=200)

    @action(methods=['post'], detail=False, permission_classes=[IsAuthenticated], url_path='batch_insertion')
    def batch_insertion(self, request):
        query_list = []
        ID_num_list = []
        for i in request.data:
            birth_date = datetime.datetime(*xldate_as_tuple(i['birth_date'], 0))
            if Student.objects.filter(ID_number=i['ID_number']).first():
                continue
            school = School.objects.filter(id=i['school']).first()
            if not school:
                school = School.objects.filter(id=1).first()
            competition_season = CompetitionSeason.objects.filter(id=i['competition_season']).first()
            if not competition_season:
                competition_season = CompetitionSeason.objects.filter(id=1).first()
            if isinstance(i.get('payment_amount', 0), str):
                if i.get('payment_amount', 0):
                    payment_amount = float('%.2f' % i['payment_amount'])
                else:
                    payment_amount = 0
            else:
                payment_amount = i['payment_amount']
            if i['ID_number'] in ID_num_list:
                continue
            else:
                ID_num_list.append(i['ID_number'])
            obj = Student(
                school=school,
                student_name=i['student_name'],
                contact_phone=i['contact_phone'],
                contact_name=i['contact_name'],
                competition_season=competition_season,
                gender=i['gender'],
                ID_number=i['ID_number'],
                payment_status=i['payment_status'],
                payment_amount=payment_amount,
                birth_date=birth_date
            )
            query_list.append(obj)
        stu = Student.objects.bulk_create(query_list)
        if stu:
            return Response(data='批量添加成功', status=200)
        else:
            return Response(data='批量添加失败', status=400)
